﻿package com.wly.ui
{
	import com.wly.adapter.ItemGridAdapter;
	import com.wly.ui.common.IItemGrid;
	import com.wly.ui.common.SpriteObject;
	
	import flash.display.BitmapData;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	
	public class ItemGrid extends SpriteObject implements IItemGrid
	{
		private var _itemCells:Array;
		private var _curItemCell:ItemCell;
		
		static public const GRIDCAPACITY:int = 8;
		
		public function ItemGrid()
		{
			super();
			initChilds();
		}
		
		private function initChilds():void
		{
			var itemCell:ItemCell;
			var i:int;
			
			_itemCells = [];
			for(i=0; i<GRIDCAPACITY; i++)
			{
				itemCell = getChildByName("mcItem"+i.toString()) as ItemCell;
				if(itemCell)
				{
					itemCell.index = i;
					itemCell.parentUI = this;
					_itemCells.push(itemCell);
				}
			}
		}
		
		protected function get adapterItemGrid():ItemGridAdapter
		{
			return adapter as ItemGridAdapter;
		}
		
		private function clearAll():void
		{
			var itemCell:ItemCell;
			var i:int;
			
			for(i=0; i<GRIDCAPACITY; i++)
			{
				itemCell = _itemCells[i] as ItemCell;
				if(itemCell)
				{
					itemCell.clearBmd();
				}
			}
		}
		
		override public function update():void
		{
			var bmd:BitmapData;
			var itemCell:ItemCell;
			var i:int;
			
			super.update();
			if(adapterItemGrid)
			{
				clearAll();
				for(i=0; i<adapterItemGrid.effLen; i++)
				{
					bmd       = adapterItemGrid.getAt(i);
					itemCell  = _itemCells[i] as ItemCell;
					if(bmd && itemCell)
					{
						itemCell.updateBmd(bmd);
					}
				}
			}
		}
		
		public function onSelect(index:int):void
		{
			var itemCell:ItemCell;
			if(_curItemCell)
			{
				_curItemCell.select = false;
			}
			if(adapterItemGrid)
			{
				adapterItemGrid.onSelect(index);
				itemCell = _itemCells[index] as ItemCell;
				_curItemCell = itemCell;
				itemCell.select = true;
			}
		}
		
		public function setTop(displayObject:DisplayObject):void
		{
			if(displayObject && displayObject.parent==this)
			{
				setChildIndex(displayObject, numChildren-1);
			}
		}
		
		public function onItemMouseOver(index:int):void
		{
		}
	}
}